package com.eduplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eduplatform.entity.TeacherSubject;
import com.eduplatform.mapper.TeacherSubjectMapper;
import com.eduplatform.service.TeacherSubjectService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TeacherSubjectServiceImpl extends ServiceImpl<TeacherSubjectMapper, TeacherSubject>
        implements TeacherSubjectService {

    @Override
    public List<Long> getSubjectIdsByTeacherId(Long teacherId) {
        LambdaQueryWrapper<TeacherSubject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeacherSubject::getTeacherId, teacherId);

        List<TeacherSubject> list = this.list(queryWrapper);
        return list.stream().map(TeacherSubject::getSubjectId).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public boolean saveTeacherSubjects(Long teacherId, List<Long> subjectIds) {
        // 先删除原有关联
        LambdaQueryWrapper<TeacherSubject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeacherSubject::getTeacherId, teacherId);
        this.remove(queryWrapper);

        // 如果没有新的学科关联，直接返回成功
        if (subjectIds == null || subjectIds.isEmpty()) {
            return true;
        }

        // 创建新的关联
        List<TeacherSubject> teacherSubjects = new ArrayList<>();
        for (Long subjectId : subjectIds) {
            TeacherSubject teacherSubject = new TeacherSubject();
            teacherSubject.setTeacherId(teacherId);
            teacherSubject.setSubjectId(subjectId);
            teacherSubjects.add(teacherSubject);
        }

        return this.saveBatch(teacherSubjects);
    }
}